//
//  QJCategoryVC.m
//  QuanJieShopProject
//
//  Created by apple on 2018/1/30.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QJCategoryVC.h"
#import "QJCategoryVCLeftCell.h"
//#import "YFCategoryVCLeftCell.h"
#import "QJCategoryVCRightCell.h"
//分类数据列表
#import "QJHomeVCClassVC.h"
#import "YFCategoryHeaderView.h"

@interface QJCategoryVC () <UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
//两个tableview
@property (nonatomic, strong) UITableView *tableViewLeft;
@property (nonatomic, strong) UICollectionView *tableViewRight;
//左侧数组
@property (nonatomic, strong) NSMutableArray *dataLeftArray;
//右侧数组
@property (nonatomic, strong) NSArray *dataRightArray;
@property (nonatomic, assign) NSInteger clickRow;
@end

@implementation QJCategoryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self categoryViewSetupAction];
    self.title = @"分类";
    
    //数据请求
    [self categoryGetLeftDataRequestAction];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNavAlpha:YES];
    //控件不被导航栏遮挡
    self.navigationController.navigationBar.translucent = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self setNavAlpha:NO];
//    self.navigationController.navigationBar.translucent = YES;
}
#pragma mark -- 获取左侧分类数据方法
- (void)categoryGetLeftDataRequestAction {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"0" forKey:@"parent_id"];
    NSLog(@"店铺分类 dict = %@", dict);
    [WWNetRequest fetchShopTypeWithParameters:dict success:^(id response) {
        NSLog(@"分类response = %@", response);
        
        NSArray *dataArr = response[@"data"];
        
        NSLog(@"class = %@", [dataArr class]);
        if ([dataArr isKindOfClass:[NSArray class]]) {
            NSMutableArray *array = [NSMutableArray array];
            // 第一级目录解析
            for (NSDictionary *dict in dataArr) { // 大健康  美食  娱乐

                CategoryLeftModel *model = [[CategoryLeftModel alloc]initWithDictionary:dict error:nil]; // 大健康
                
                NSMutableArray *tempSubArr = [NSMutableArray array];
                NSArray *subArr = dict[@"data"];
                // 第二级目录解析
                for (NSDictionary *subDict in subArr) { // 保健外用/养老/保健内服
                    CategoryLeftModel *subModel = [[CategoryLeftModel alloc]initWithDictionary:subDict error:nil];
                    
                    // 第三级目录解析
                    NSMutableArray *detailArr = [NSMutableArray array];
                    NSArray *dateilArr = subDict[@"data"];
                    for (NSDictionary *detailDict in dateilArr) {
                        CategoryLeftModel *detailModel = [[CategoryLeftModel alloc]initWithDictionary:detailDict error:nil];
                        [detailArr addObject:detailModel];
                    }
                    subModel.subArr = detailArr;
                    
                    [tempSubArr addObject:subModel];
                }
                
                model.subArr = tempSubArr;
                
                [array addObject:model];
            };
            _dataLeftArray = array;
        }
        [_tableViewLeft reloadData];
        if (_dataLeftArray.count > 0) {
            //默认选中下标0的cell
            NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:0];
            [_tableViewLeft selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionBottom];
            CategoryLeftModel *model = _dataLeftArray[0];
            _clickRow = 0;
            model.ifClick = @"1";
            [_dataLeftArray replaceObjectAtIndex:0 withObject:model];
            NSArray *rightArr = model.subArr;
            _dataRightArray = rightArr;
            [_tableViewRight reloadData];
        }
        
    } failure:^(NSDictionary *error) {
        NSLog(@"店铺分类 error=%@", error);
    }];
}
#pragma mark -- 界面布局方法
- (void)categoryViewSetupAction{
    _tableViewLeft = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 120 * [UIScreen mainScreen].bounds.size.width / 375.0, UISCREEN_HEIGHT - 49) style:UITableViewStylePlain];
    _tableViewLeft.backgroundColor = HexRGB(0xe6e6e6);
    _tableViewLeft.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableViewLeft.delegate = self;
    _tableViewLeft.dataSource = self;
    [self.view addSubview:_tableViewLeft];
    //解决表无故偏移
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //大小
    layout.itemSize = CGSizeMake((UISCREEN_WIDTH - 125 * [UIScreen mainScreen].bounds.size.width / 375.0) / 2.0, (UISCREEN_WIDTH - 125 * [UIScreen mainScreen].bounds.size.width / 375.0) / 2.0);
    //最小行间距
    layout.minimumLineSpacing = 0 * [UIScreen mainScreen].bounds.size.height / 667.0;
    //最小列间距
    layout.minimumInteritemSpacing = 0 * [UIScreen mainScreen].bounds.size.width / 375.0;
    //滚动方向(默认垂直)
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _tableViewRight = [[UICollectionView alloc]initWithFrame:CGRectMake(120 * [UIScreen mainScreen].bounds.size.width / 375.0, 0, UISCREEN_WIDTH - 120 * [UIScreen mainScreen].bounds.size.width / 375.0, UISCREEN_HEIGHT - 49) collectionViewLayout:layout];
    _tableViewRight.backgroundColor = [UIColor whiteColor];
    _tableViewRight.delegate = self;
    _tableViewRight.dataSource = self;
    //在cell的个数不多的时候也可以竖直滑动
    _tableViewRight.alwaysBounceVertical = YES;
    [_tableViewRight registerNib:[UINib nibWithNibName:@"QJCategoryVCRightCell" bundle:nil] forCellWithReuseIdentifier:@"itemId"];
    [self.view addSubview:_tableViewRight];
    
    // headerView
//    [_tableViewRight registerClass:[YFCategoryHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YFCategoryHeaderView"];
    
    [_tableViewRight registerNib:[UINib nibWithNibName:@"YFCategoryHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YFCategoryHeaderView"];

}
#pragma mark -- 左侧tableview布局
#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataLeftArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"QJCategoryVCLeftCell";
    QJCategoryVCLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    CategoryLeftModel *model = _dataLeftArray[indexPath.row];

    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"QJCategoryVCLeftCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [cell cellUpdateWithModel: model];
    return cell;

}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //点击选中cell
    NSIndexPath *ip = indexPath;
    [_tableViewLeft selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionBottom];
    //将原来选中的设为未选中
    CategoryLeftModel *clickModel = _dataLeftArray[_clickRow];
    clickModel.ifClick = @"0";
    [_dataLeftArray replaceObjectAtIndex:_clickRow withObject:clickModel];
    //设置新的选中cell
    CategoryLeftModel *model = _dataLeftArray[indexPath.row];
    model.ifClick = @"1";
    
    // replaceObjectAtIndex 这个方法在安全机制里没有判断
    [_dataLeftArray replaceObjectAtIndex:indexPath.row withObject:model];
    _clickRow = indexPath.row;
//    NSArray *arr = model.twoCategory;
//    _dataRightArray = arr;
    
    [_tableViewLeft reloadData];
    [_tableViewRight reloadData];
}
#pragma mark -- 右侧collectionview布局
#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    CategoryLeftModel *model = _dataLeftArray[_clickRow]; // 大健康
    return model.subArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    CategoryLeftModel *model = _dataLeftArray[_clickRow]; // 大健康
    CategoryLeftModel *subModel = model.subArr[section];  // 保健外用
    return subModel.subArr.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    QJCategoryVCRightCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"itemId" forIndexPath:indexPath];
    [cell cellDefaultUIPrepare];
    
    CategoryLeftModel *model = _dataLeftArray[_clickRow]; // 大健康
    CategoryLeftModel *subModel = model.subArr[indexPath.section]; // 保健外用
    CategoryLeftModel *detailModel = subModel.subArr[indexPath.row];
    
    [cell cellUpdateWithModel:detailModel];
    return cell;
}

#pragma mark -- 区头(显示二级目录)
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        CategoryLeftModel *model = _dataLeftArray[_clickRow]; // 大健康
        CategoryLeftModel *subModel = model.subArr[indexPath.section]; // 保健外用
        
        //区头
        YFCategoryHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YFCategoryHeaderView" forIndexPath:indexPath];
        headerView.titleLabel.text = subModel.name;
        return headerView;
    }else {
        //区尾
        return nil;
    }
    return nil;
}

#pragma mark -- 区头的高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    YFHomeZeroReusableView *testView= [[YFHomeZeroReusableView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 0)];
    
    return CGSizeMake(UISCREEN_WIDTH, 44);
}

#pragma mark --  UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //一级数据参数
    CategoryLeftModel *leftModel = self.dataLeftArray[self.clickRow];
    NSString *categoryidStr = [NSString stringWithoutNilFormart:leftModel.udid];
    //二级数据参数
    
    CategoryLeftModel *rightModel = leftModel.subArr[indexPath.section];
    CategoryLeftModel*tmpModel =  rightModel.subArr[indexPath.row];
    NSString *twoCategoryIdStr = [NSString stringWithoutNilFormart:tmpModel.udid];
    QJHomeVCClassVC *VC = [[QJHomeVCClassVC alloc]init];
    VC.classID = categoryidStr;
    VC.classTwoID = twoCategoryIdStr;
    KPushViewControllerAction(VC);
}
#pragma mark -- 懒加载
-(NSMutableArray *)dataLeftArray{
    if (!_dataLeftArray) {
        _dataLeftArray = [NSMutableArray array];
    }
    return _dataLeftArray;
}
-(NSArray *)dataRightArray{
    if (!_dataRightArray) {
        _dataRightArray = [NSArray array];
    }
    return _dataRightArray;
}

@end
